package com.isyscore.exception;

import com.isyscore.utils.MesResult;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理
 * @author 云内核
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(FjMesException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public MesResult handleFjMesException(FjMesException ex) {
        // 返回自定义的错误消息和状态码
        ex.printStackTrace();
        return MesResult.error(ex.getCode(),ex.getMessage());
    }
    @ExceptionHandler(AuthorizationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public ResponseEntity<?> handleAuthorizationException(AuthorizationException ex) {
        ex.printStackTrace();
        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body("没有权限访问");
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public ResponseEntity<?> handleUnauthorizedException(UnauthorizedException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body("未授权访问");
    }

    @ExceptionHandler(UnauthenticatedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public ResponseEntity<?> handleUnauthenticatedException(UnauthenticatedException e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body("请先登录");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ResponseBody
    public Map<String, Object> handleRuntimeException(RuntimeException ex) {
        ex.printStackTrace();
        Map<String, Object> response = new HashMap<>();
        response.put("error", ex.getMessage());
        return response;
    }


    @ExceptionHandler(Exception.class)
    public MesResult handleGeneralException(Exception ex) {
        ex.printStackTrace();
        return MesResult.error(ex.toString());
    }
}
